from flask import session
from flask_script import Manager
from flask_migrate import MigrateCommand
from info import create_app

# 创建应用
app = create_app("dev")
# 创建一个manage管理者
mgr = Manager(app)
# (2).添加迁移命令
mgr.add_command("mc", MigrateCommand)



# 将生成管理员的操作先封装成函数, 再将该函数包装成命令
@mgr.option("-u", dest="username")   #  python main.py create_superuser -u admin -p 123456
@mgr.option("-p", dest="password")
def create_superuser(username, password):

    if not all([username, password]):
        print("参数不完整")
        return

    from info.models import User
    from info import db

    # 生成用户模型, 设置is_admin=True
    user = User()
    user.mobile = username
    user.password = password
    user.nick_name = username
    user.is_admin = True
    try:
        db.session.add(user)
        db.session.commit()
    except BaseException as e:
        app.logger.error(e)
        db.session.rollback()
        print("数据库添加失败")

    print("管理员注册成功")



if __name__ == '__main__':
    mgr.run()
